<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <!-- 搜索框 -->
        <el-input
          placeholder="请输入搜索内容"
          v-model="required_parameter.query"
          clearable
          @clear="getData"
          class="searchinput"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="getData"
          ></el-button>
        </el-input>

        <!-- 添加用户 -->
        <el-button type="primary" class="add" @click="addDialogVisible = true"
          >添加用户</el-button
        >
      </el-row>
      <!-- 用户列表区 -->
      <el-row>
        <el-table :data="accept" border stripe>
          <el-table-column label="#" type="index"> </el-table-column>
          <el-table-column prop="username" label="姓名"> </el-table-column>
          <el-table-column prop="email" label="邮箱"> </el-table-column>
          <el-table-column prop="mobile" label="电话"> </el-table-column>
          <el-table-column prop="role_name" label="角色"> </el-table-column>
          <el-table-column prop="mg_state" label="状态">
            <template v-slot:default="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="userState(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot:default="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="small"
                @click="amendUsersInfo(scope.row.id)"
              ></el-button>
              <!-- 删除按钮 -->
              <el-button
                type="warning"
                icon="el-icon-delete"
                size="small"
                @click="deleteUsers(scope.row.id)"
              ></el-button>
              <!-- 分配角色按钮 -->
              <el-button
                type="danger"
                icon="el-icon-s-tools"
                size="small"
                @click="allotRole(scope.row)"
              ></el-button>
            </template>
            <!-- 修改按钮 -->
          </el-table-column>
        </el-table>
      </el-row>
      <el-row>
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="required_parameter.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="required_parameter.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </el-row>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="resetAdd"
    >
      <!-- 主体 -->
      <el-form :model="addForm" :rules="rules" ref="addForm" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="amendUserDialog"
      width="50%"
      @close="amendFormReset"
    >
      <!-- 主体 -->
      <el-form
        :model="amendForm"
        :rules="rules"
        ref="amendForm"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="amendForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="amendForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="amendForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="amendUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="amendFormQuest">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="allotDialog"
      width="50%"
      @close="reset"
    >
      <div>
        <p>当前的用户:{{ userInfo.username }}</p>
        <p>当前的角色:{{ userInfo.role_name }}</p>
        <p>
          分配新角色:
          <el-select v-model="checkListId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "users",
  data() {
    // 验证邮箱正则
    var checkAge = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        // 合法邮箱
        return callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };
    // 验证手机号正则
    var checkMobile = (rule, value, callback) => {
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        // 合法邮箱
        return callback();
      }
      callback(new Error("请输入合法的手机号"));
    };
    return {
      // 搜索关键词
      search: "",
      userData: {},
      // 请求参数
      required_parameter: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      },
      // 接收参数
      accept: [],
      // 总数据条数
      total: 0,
      // 控制添加用户对话框
      addDialogVisible: false,
      // 添加用户表单数据对象   里面可以不写key value0
      addForm: { username: "", password: "", email: "", mobile: "" },
      //  添加用户校验表单规则对象
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkAge, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 控制修改用户对话框
      amendUserDialog: false,
      // 修改用户表单信息
      amendForm: {
        username: "",
        email: "",
        mobile: "",
      },
      allotDialog: false,

      // 用户信息
      userInfo: {},
      // 角色列表
      rolesList: [],
      // 下拉菜单选择的值
      checkListId: "",
    };
  },
  created() {
    this.getData();
  },
  methods: {
    // 请求页面数据
    async getData() {
      const { data: res } = await this.$http.get("users", {
        params: this.required_parameter,
      });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.required_parameter.pagenum = res.data.pagenum;
      this.total = res.data.total;
      this.accept = res.data.users;
      console.log(this.pagenum);
      console.log(this.total);
      console.log(this.accept);
    },
    // 获取最新pagesize
    handleSizeChange(newsize) {
      console.log(newsize);
      this.required_parameter.pagesize = newsize;
      this.getData();
    },
    // 监听页码改变
    handleCurrentChange(newpage) {
      console.log(newpage);
      this.required_parameter.pagenum = newpage;
      this.getData();
    },
    // 修改用户状态
    async userState(user) {
      console.log(user);
      const { data: res } = await this.$http.put(
        `users/${user.id}/state/${user.mg_state}`
      );
      console.log(res);
      if (res.meta.status !== 200) {
        // 如修改失败还是改为原状态
        user.mg_state = !user.mg_state;
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
      // this.getData();
    },
    // 添加用户表单关闭时，重置表单
    resetAdd() {
      this.$refs.addForm.resetFields();
    },
    // 添加用户表单预校验
    addUser() {
      this.$refs.addForm.validate(async (valid) => {
        console.log(valid);
        if (!valid) {
          return;
        }
        // 发送http请求
        const { data: res } = await this.$http.post("users", this.addForm);
        console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg);
        }
        this.$message.success(res.meta.msg);
        this.addDialogVisible = false;
        this.getData();
      });
    },
    // 根据ID查询用户信息
    async amendUsersInfo(id) {
      this.amendUserDialog = true;

      const { data: res } = await this.$http.get("users/" + id);

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.amendForm = res.data;
      console.log(this.amendForm);
    },
    // 重置修改表单
    amendFormReset() {
      this.$refs.amendForm.resetFields();
    },
    // 修改表单的预校验和网络请求
    amendFormQuest() {
      this.$refs.amendForm.validate(async (valid) => {
        console.log(valid);
        if (!valid) {
          return this.$message.info("修改正确信息");
        }
        const { data: res } = await this.$http.put(
          "users/" + this.amendForm.id,
          {
            email: this.amendForm.email,
            mobile: this.amendForm.mobile,
          }
        );
        if (res.meta.status != 200) {
          return this.$message.error(res.meta.msg);
        }
        this.amendForm = res.data;
        this.getData();
        this.amendUserDialog = false;
        this.$message.success(res.meta.msg);
        console.log(this.amendForm);
      });
    },
    // 删除用户
    async deleteUsers(id) {
      const ress = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      // 点击确认ress为 confirm
      // 点击取消ress为 cancel
      if (ress != "confirm") {
        return this.$message.info("取消了删除");
      }
      // 发送删除用户请求
      const { data: res } = await this.$http.delete("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      console.log(res);
      this.getData();
      this.$message.success(res.meta.msg);
    },
    // 点击分配角色按钮，存储用户信息，获取角色列表
    async allotRole(role) {
      this.allotDialog = true;
      this.userInfo = role;
      // console.log(role);

      // 获取角色列表

      const { data: res } = await this.$http.get("roles");
      if (res.meta.status != 200) {
        return this.$message.error("失败");
      }
      this.rolesList = res.data;
      console.log(this.rolesList);
    },
    // 点击确认分配角色
    async saveRoleInfo() {
      if (!this.checkListId) {
        return this.$message.info("请选择分配新角色");
      }
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.checkListId,
        }
      );
      if (res.meta.status != 200) {
        return this.$message.error("分配失败");
      }
      this.$message.success("分配成功");
      this.getData();
      console.log(res);
      this.allotDialog = false;
    },
    // 关闭分配角色对话框后重置信息
    reset() {
      this.userInfo = "";
      this.checkListId = "";
    },
  },
};
</script>

<style lang='less' scoped>
.el-breadcrumb {
  font-size: 16px;
}

.el-input {
  width: 30%;
}
.add {
  margin-left: 20px;
}
.el-table {
  margin-top: 20px;
  text-align: center;
}
.el-pagination {
  margin-top: 20px;
}
.el-input {
  width: 100%;
}
.searchinput {
  width: 30%;
}
</style>